﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Collections;

namespace Liquid.Collections {
	/// <summary>
	/// A collection where all items are stored using a <see cref="System.WeakReference"/>.
	/// </summary>
	/// <typeparam name="T">The type of the items in the collection</typeparam>
	public class WeakCollection<T> : ICollection<T>, IChangeNotifyingEnumerable<T>
		where T : class {
		ChangeNotifyingCollection<WeakReference> inner;

		protected ChangeNotifyingCollection<WeakReference> Inner {
			get { return inner; }
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="WeakCollection&lt;T&gt;"/> class.
		/// </summary>
		public WeakCollection() {
			this.inner = new ChangeNotifyingCollection<WeakReference>();
			inner.Added += new ItemSetEventHandler<WeakReference>(inner_Added);
			inner.Removed += new ItemSetEventHandler<WeakReference>(inner_Removed);
		}

		void inner_Added(object sender, ItemSetEventArgs<WeakReference> e) {
			OnAdded(new ItemSetEventArgs<T>(SelectAlive(e.Items)));
		}

		void inner_Removed(object sender, ItemSetEventArgs<WeakReference> e) {
			OnRemoved(new ItemSetEventArgs<T>(SelectAlive(e.Items)));
		}

		/// <summary>
		/// Occurs when a set of items is added.
		/// </summary>
		public event ItemSetEventHandler<T> Added;
		/// <summary>
		/// Raises the <see cref="E:Added"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Liquid.Collections.ItemSetEventArgs&lt;T&gt;"/> instance containing the event data.</param>
		protected void OnAdded(ItemSetEventArgs<T> e) {
			var handler = Added;
			if (handler != null)
				handler(this, e);
		}

		/// <summary>
		/// Occurs when a set of items are removed.
		/// </summary>
		public event ItemSetEventHandler<T> Removed;
		/// <summary>
		/// Raises the <see cref="E:Removed"/> event.
		/// </summary>
		/// <param name="e">The <see cref="Liquid.Collections.ItemSetEventArgs&lt;T&gt;"/> instance containing the event data.</param>
		protected void OnRemoved(ItemSetEventArgs<T> e) {
			var handler = Removed;
			if (handler != null)
				handler(this, e);
		}

		#region ICollection<T> Members

		/// <summary>
		/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </summary>
		/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
		public void Add(T item) {
			inner.Add(new WeakReference(item));
			if (ShouldCompact()) Compact();
		}

		/// <summary>
		/// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </summary>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception>
		public void Clear() {
			inner.Clear();
		}

		/// <summary>
		/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
		/// </summary>
		/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
		/// <returns>
		/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
		/// </returns>
		public bool Contains(T item) {
			if (ShouldCompact()) Compact();
			var q = from wr in inner
					where IsEqual(wr, item)
					select item;
			return q.Any();
		}

		/// <summary>
		/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
		/// </summary>
		/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
		/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
		/// <exception cref="T:System.ArgumentNullException">
		/// 	<paramref name="array"/> is null.</exception>
		/// <exception cref="T:System.ArgumentOutOfRangeException">
		/// 	<paramref name="arrayIndex"/> is less than 0.</exception>
		/// <exception cref="T:System.ArgumentException">
		/// 	<paramref name="array"/> is multidimensional.-or-<paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>.-or-The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.-or-Type <paramref name="T"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception>
		public void CopyTo(T[] array, int arrayIndex) {
			// Make a copy to avoid a partial copy
			// incase there are too many alive objects
			var temp = Compact();
			temp.CopyTo(array, arrayIndex);
		}

		/// <summary>
		/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </summary>
		/// <value></value>
		/// <returns>The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</returns>
		public int Count {
			get {
				if (ShouldCompact()) Compact();
				return SelectAlive(inner).Count();
			}
		}

		bool ICollection<T>.IsReadOnly {
			get { return false; }
		}

		/// <summary>
		/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </summary>
		/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
		/// <returns>
		/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
		/// </returns>
		/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception>
		public bool Remove(T item) {
			try {
				return inner.Remove(wr => wr.Target == item);
			} finally {
				if (ShouldCompact()) Compact();
			}
		}

		#endregion

		static IEnumerable<T> SelectAlive(IEnumerable<WeakReference> source) {
			foreach (var item in source) {
				var target = item.Target;
				if (item.IsAlive)
					yield return (T)target;
			}
		}

		#region IEnumerable<T> Members

		/// <summary>
		/// Returns an enumerator that iterates through the collection.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
		/// </returns>
		public IEnumerator<T> GetEnumerator() {
			if (ShouldCompact()) Compact();
			return SelectAlive(inner).GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator() {
			return this.GetEnumerator();
		}

		#endregion

		protected virtual bool ShouldCompact() {
			return false;// TODO: Should WeakCollection itself ever Compact?
		}
		protected IList<T> Compact() {
			var copy = this.ToArray();
			Inner.RemoveAll(wr => !wr.IsAlive);
			return copy;
		}

		protected static bool IsEqual(WeakReference wr, T item) {
			return EqualityComparer<T>
				.Default
				.Equals(Convert(wr), item);
		}
		protected static T Convert(WeakReference wr) {
			object target = wr.Target;
			if (!wr.IsAlive)
				return default(T);
			return (T)target;
		}

		public T[] ToArray() {
			// TODO: Is there a better way to do WeakCollection<T>.ToArray()?
			return Enumerable.ToArray(this);
		}
	}
}
